package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.dto.ContractDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.ContractMapper;
import com.mg.mapper.MachineTypeMapper;
import com.mg.mapper.PurchaseRecordMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.Contract;
import com.mg.model.MachineType;
import com.mg.model.PurchaseRecord;
import com.mg.model.User;
import com.mg.service.ContractService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class ContractServiceImpl implements ContractService {
    @Autowired
    private MachineTypeMapper machineTypeMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;


    private Logger logger = LogManager.getLogger(ContractServiceImpl.class.getName());

    @Override
    public List<MachineType> getAllMachineTypes() {
        return machineTypeMapper.selectAll();
    }

    @Override
    public PageInfo<ContractDto> selectPageInfo(ContractDto contractDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        List<ContractDto> contractDtos = contractMapper.selectPageInfo(contractDto);
        PageInfo<ContractDto> userDtoPageInfo = new PageInfo<>(contractDtos);
        return userDtoPageInfo;
    }

    @Override
    public PageInfo<Map<String, Object>> findContractPage(Map<String, Object> paramMap, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        ContractDto contractDto = new ContractDto();
        contractDto.setId(21);
        List<Map<String, Object>> contractDtos = contractMapper.findContractPage(paramMap);
        PageInfo<Map<String, Object>> userDtoPageInfo = new PageInfo<>(contractDtos);
        return userDtoPageInfo;
    }

    @Override
    public SimpleResult buyContract(Integer userId, BigDecimal num, Integer contractId) {
        SimpleResult result = new SimpleResult();
        Contract contract = new Contract();
        contract.setId(contractId);
        contract = contractMapper.selectOne(contract);
        if (contract.getStock().compareTo(new BigDecimal(0.00)) < 1) {
            result.setMsg("该合约已经售罄，请选择其他合约");
            result.setSuccess(false);
        } else {
            if (contract.getStock().compareTo(num) > -1) {
                BigDecimal money = contract.getPrice().multiply(num);
                User user = new User();
                user.setId(userId);
                user = userMapper.selectOne(user);
                BigDecimal availableMoney = user.getBalance().subtract(user.getFrozeMoney());
                if (money.compareTo(availableMoney) > 0) {
                    result.setMsg("可用用余额不足请充值!");
                    result.setSuccess(false);
                } else {
                    BigDecimal frozeMoney=user.getFrozeMoney().add(money);
                    user=new User();
                    user.setId(userId);
                    user.setFrozeMoney(frozeMoney);
                    userMapper.updateByPrimaryKeySelective(user);
                    PurchaseRecord purchaseRecord= new PurchaseRecord();
                    purchaseRecord.setUserId(userId);
                    purchaseRecord.setContractId(contractId);
                    purchaseRecord.setPrice(contract.getPrice());
                    purchaseRecord.setState("未审核");
                    purchaseRecord.setCreateTime(new Date());
                    purchaseRecord.setMoney(money);
                    purchaseRecord.setNumber(num);
                    purchaseRecord.setComputingPower(contract.getComputingPower().multiply(num));
                    purchaseRecordMapper.insert(purchaseRecord);
                    BigDecimal stock = contract.getStock().subtract(num);
                    contract = new Contract();
                    contract.setId(contractId);
                    contract.setStock(stock);
                    contractMapper.updateByPrimaryKeySelective(contract);
                }
            } else {
                result.setSuccess(false);
                result.setMsg("该合约库存不足，请刷新系统重新，购买");
            }
        }
        return result;
    }

    @Override
    public SimpleResult insertContract(Contract contract) {
        SimpleResult result = new SimpleResult();
        try {
            contract.setCreateTime(new Date());
            contractMapper.insert(contract);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增合约信息失败 系统未知异常");
            logger.error("新增合约信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updateContract(Contract contract) {
        SimpleResult result = new SimpleResult();
        try {
            Contract contract1 = new Contract();
            contract1.setId(contract.getId());
            contract1 = contractMapper.selectOne(contract1);
            if (contract1 == null) {
                result.setSuccess(false);
                result.setMsg("该合约部不存在，请刷新重试！");
            } else {
                contract.setUpdateTime(new Date());
                contractMapper.updateByPrimaryKeySelective(contract);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新合约信息失败 系统未知异常");
            logger.error("更新合约信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deleteContract(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                contractMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除合约信失败 系统未知异常");
            logger.error("删除合约信失败 系统未知异常", e);
        }
        return result;
    }
}
